//使用require.context
    //1.一个要搜索的目录
    //2.一个标记表示是否还要搜索其子目录
    //3.一个匹配文件的正则表达式
let files = require.context("../pages",true,/\.vue$/)
//console.log(files);
//console.log(files.keys());

//路由配置

let repeatRoutes = files.keys().map(path => {
    //console.log(path);
    //1.需要把path: ./home/users/index.vue 变成 /home/users 这样的
    //使用正则过滤掉 /index.vue 或者 .vue
    let regExp = /(\/index\.vue|\.vue)$/
    let com = files(path).default;
    path = path.replace(regExp,"").substring(1)
    //console.log(com.meta);
    return {
        //路由的重定向
        redirect: com.redirect ?? null,
        //具名路由
        name:com.name ?? path.substring(1).split("/").join("-"),
        meta:com.meta ?? {},   //路由元信息
        path:path.toLowerCase(),
        component:()=>import("@/pages"+path)
    }
});
//console.log(repeatRoutes);    //扁平化的路由配置

//需要把repeatRoutes转换成树形数据
const convertTree = (repeatRoutes) => {
    //每条数据添加id，如果是嵌套路由，要加上pid
    //将path作为当前对象的id

    let treeRoues = []   //声明一个空数组用于存放树形的routes配置
    //时间复杂度o(n^2)

    //遍历repeatRoutes，对数据的id进行处理
    repeatRoutes.forEach(route => { 
        //把path作为id
        let pathArr = route.path.substring(1).split("/")
        //console.log(pathArr);
        //给每个对象生成id
        route.id = pathArr.join("-")
        //如果数组长度>1，说明是子路由，需要添加pid
        if(pathArr.length>1){
            //pid就是父id，数组中最后一项取掉就是父id了
            let pidArr = [...pathArr]  //浅拷贝
            pidArr.pop()
            route.pid = pidArr.join("-")
        }else{
            route.id = pathArr.join("-")
        }
        //console.log(route);
    })  
    
    //把平铺数据，变成嵌套的树形数据
    repeatRoutes.forEach(route=>{
        //先找爸爸的pid和数据id相等的项
        let parent = repeatRoutes.find(v=>v.id===route.pid)
        //console.log(parent);
        if(parent){
            //当前的route对象找到父节点了
                //判断父节点有没有children属性，没有就创建
            if(!parent.children){
                parent.children = []
            }
            //console.log(route.path);
            route.path = route.path.split("/").pop()    //["","home","users","aa"]
            parent.children.push(route)
            //console.log(route.path);
        }else{
            treeRoues.push(route)
        }
    })
    return treeRoues
}
let result = convertTree(repeatRoutes)
console.log(result)

export default result